package com.cloudcc.boot.oaservice;

import com.cloudcc.boot.constants.UtilConstants;
import com.cloudcc.boot.core.CCObject;
import com.cloudcc.boot.core.CCService;
import com.cloudcc.boot.core.ServiceResult;
import com.cloudcc.boot.model.UserRequest;
import com.cloudcc.boot.web.OA_Operate;
import com.cloudcc.boot.web.OA_Token;
import com.google.common.collect.Lists;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import static com.cloudcc.boot.core.CCService.userInfo;

@Controller
@RequestMapping(value = "/api")
@Slf4j
public class xmlxClass {
    @Value("${system.localurl:''}")
    public String localurl;
    @Value("${system.url:''}")
    public String url;
    @Value("${system.oaurl:''}")
    public String oaurl;
    @Autowired
    public OA_Token oa;
    @Autowired
    private OA_Operate oa_operate;
    String xmlx_workflowId= UtilConstants.Public.xmlx_workflowId;//流程ID
    String xmlx_xmht_tableDBName= UtilConstants.Public.xmlx_xmht_tableDBName;////项目立项_项目合同子表表名
    String xmlx_cbcs_tableDBName= UtilConstants.Public.xmlx_cbcs_tableDBName;////项目立项_成本测算_子表表名
    /**
     * author : 黄涛 on 2024-07-08
     * 项目立项推送OA
     */
    @ResponseBody
    @RequestMapping(value = "/xmlx_push", produces = "text/html;charset=UTF-8")
    @ApiOperation(value = "")
    public String xmlx_push(UserRequest userRequest, HttpServletRequest request) throws Exception {
        String userRquestStr = JSONObject.fromObject(userRequest).toString();//入参
        log.info("xmlx_push请求参数{}", userRquestStr);
        JSONObject returnJson = new JSONObject();
        CCObject interfacerecordObj = new CCObject("interfacerecord");//接口同步记录
        CCService cs = new CCService(userInfo);

        try {
            String recordID = userRequest.getRecordID() == null ? "" : userRequest.getRecordID();//主表记录ID
            String objectApiName = "xmlx";//对象名
            String isnextflow = "0";//isnextflow ：新建流程是否默认提交到第二节点，可选值为[0 ：不流转 1：流转 (默认)]
            String oa_user_type = "主账号";//账号类型：主账号、次账号
            //查询oa经办人ID
            String oa_user_id = oa_operate.getOaUserId(objectApiName,recordID,oa_user_type);
            String owneridccname = oa_operate.getCRMOwner(objectApiName,recordID);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date nowDate = new Date(); // 当前日期Date
            String currentTime = sdf.format(nowDate);
            //处理主表
            List<JSONObject> mainList = oa_operate.dealOAMainParam(objectApiName,recordID,"项目立项", oa_user_type);
            //处理子表
            List<JSONObject> subList = Lists.newArrayList();
            List<JSONObject> subOneList = oa_operate.dealOAhtSubParam(objectApiName,recordID,"id","项目合同");//子表(主表转子表)：项目合同
            if(CollectionUtils.isNotEmpty(subOneList)){
                JSONObject object = new JSONObject();
                object.put("tableDBName",xmlx_xmht_tableDBName);
                object.put("workflowRequestTableRecords",subOneList);
                subList.add(object);
            }
            List<JSONObject> subTwoList = oa_operate.dealOASubParam("lxcbcs",recordID,"xmlx","立项-成本测算", oa_user_type);//子表：成本测算
            if(CollectionUtils.isNotEmpty(subTwoList)){
                JSONObject object = new JSONObject();
                object.put("tableDBName",xmlx_cbcs_tableDBName);
                object.put("workflowRequestTableRecords",subTwoList);
                subList.add(object);
            }
            if(CollectionUtils.isEmpty(mainList)){
                returnJson.put("code", "ERROR");
                returnJson.put("errMsg", "主表数据为空！");
                return returnJson.toString();
            }
            log.info("===================================");
            log.info("list==size{}==={}", mainList.size(), JSONArray.fromObject(mainList).toString());
            JSONObject param = new JSONObject();
            param.put("mainData",mainList);
            if(CollectionUtils.isNotEmpty(subList)){
                param.put("detailData",subList);
            }
            JSONObject otherParams = new JSONObject();
            otherParams.put("isnextflow",isnextflow);
            param.put("otherParams",otherParams);
            param.put("workflowId",xmlx_workflowId);
            param.put("requestName","项目立项-"+owneridccname+"-"+currentTime);
            //TODO 调接口传 param
            String oa_path =oaurl+"/api/workflow/paService/doCreateRequest";//OA创建流程接口
            log.info("osSendPost-->oa_path参数：{}",oa_path);
            log.info("osSendPost-->oa_user_id参数：{}",oa_user_id);
            log.info("osSendPost-->param参数：{}",param.toString());
            String data = oa.osSendPost(oa_path,oa_user_id,param.toString());
            log.info("========================");
            log.info("OA返回参数：：" + data);
            if (data.length()>0){
                returnJson = JSONObject.fromObject(data);
            }else {
                returnJson.put("code", "ERROR");
                returnJson.put("errMsg", "OA接口无返回");
            }
            interfacerecordObj.put("url", oa_path);//url
            interfacerecordObj.put("crcs", param.toString());//传入参数
            interfacerecordObj.put("zxzt", "处理成功");//执行状态
        } catch (Exception e) {
            returnJson.put("code", "ERROR");
            returnJson.put("errMsg", e + "");

            log.info("========================");
            log.info("报错信息："+e.toString());

            interfacerecordObj.put("zxzt", "处理失败");//执行状态
        } finally {
            interfacerecordObj.put("fhcs", returnJson.toString());//返回参数
            //写入数据 newObj
            ServiceResult sr = cs.insert(interfacerecordObj);
        }
        return returnJson.toString();
    }

    /**
     * author : 黄涛 on 2024-07-08
     * 接收OA回写项目立项数据
     */
    @ResponseBody
    @RequestMapping(value = "/xmlx_receive", produces = "text/html;charset=UTF-8")
    @ApiOperation(value = "")
    public String xmlx_receive(@RequestBody UserRequest userRequest, HttpServletRequest request) throws Exception {
        String userRquestStr = JSONObject.fromObject(userRequest).toString();//入参
        log.info("xmlx_receive请求参数{}", userRquestStr);
        JSONObject returnJson = new JSONObject();
        CCService cs = new CCService(userInfo);
        CCObject interfacerecordObj = new CCObject("interfacerecord");//接口同步记录
        interfacerecordObj.put("url", localurl+"api/xmlx_receive");//url
        interfacerecordObj.put("crcs", userRquestStr);//传入参数

        try {
            String dataStr = userRequest.getData() == null ? "" : userRequest.getData().toString();//data数据
            String objectApiName = "xmlx";//对象名
            log.info("========================");
            log.info("data参数：：" + dataStr);
            if (dataStr.length() == 0) {
                returnJson.put("result", "false");
                returnJson.put("returnInfo", "data数据为空！");
                return returnJson.toString();
            }
            List<CCObject> main_List = JSONArray.fromObject(dataStr);
            JSONObject mainObj = new JSONObject();
            if (main_List != null && main_List.size() > 0) {
                mainObj = JSONObject.fromObject(main_List.get(0));
            }
            if (mainObj != null && mainObj.size() == 0) {
                returnJson.put("result", "false");
                returnJson.put("returnInfo", "主表数据为空！");
                return returnJson.toString();
            }

            //立项-成本测算子表
            if (mainObj.containsKey("cbDetail")){
                String cbDetailStr = mainObj.getString("cbDetail");
                log.info("subOneList子表传入数据========="+cbDetailStr);
                if (cbDetailStr.length()>0){
                    JSONArray cbDetailStrArr = JSONArray.fromObject(cbDetailStr);
                    List<JSONObject> subOneList = oa_operate.dealCRMSubParam(cbDetailStrArr, "立项-成本测算");//子表：销售内容
                    log.info("subOneList子表转换后数据=============="+subOneList.toString());
                    if (CollectionUtils.isNotEmpty(subOneList)) {
                        String subObjectApiName= "lxcbcs";
                        String oneArrayStr = subOneList.toString();
                        //接口推送
                        JSONObject parObj = new JSONObject();
                        parObj.put("serviceName", "upsert"); //服务名
                        parObj.put("objectApiName", subObjectApiName); //对象名
                        parObj.put("data", oneArrayStr); //查询条件
                        String relStr = cs.CCPost(cs.path, parObj.toString());
                        log.info("subOneList子表保存结果============"+relStr);
                    }
                }
            }
            //项目立项主表
            List<JSONObject> mainList = oa_operate.dealCRMMainParam(objectApiName, mainObj, "项目立项");
            log.info("转换后主表数据==========" + mainList);
            //主表数据保存
            String putArrayStr = mainList.toString();
            //接口推送
            JSONObject parObj = new JSONObject();
            parObj.put("serviceName", "upsert"); //服务名
            parObj.put("objectApiName", objectApiName); //对象名
            parObj.put("data", putArrayStr); //查询条件
///            System.out.println("parObj = " + parObj);
            String relStr = cs.CCPost(cs.path, parObj.toString());

            returnJson = JSONObject.fromObject(relStr);
            log.info("保存主表数据返回结果：=======" + returnJson);
            interfacerecordObj.put("zxzt", "处理成功");//执行状态
        } catch (Exception e) {
            returnJson.put("result", "false");
            returnJson.put("returnInfo", e + "");
            returnJson.put("returnCode", "-1");

            log.info("========================");
            log.info("报错信息：" + e.toString());

            interfacerecordObj.put("zxzt", "处理失败");//执行状态
        } finally {
            interfacerecordObj.put("fhcs", returnJson.toString());//返回参数
            //写入数据 newObj
            ServiceResult sr = cs.insert(interfacerecordObj);
        }
        return returnJson.toString();
    }
}
